package com.bolt.admin.security.shiro.session;

import com.bolt.admin.module.sys.service.OnlineUserService;
import com.bolt.admin.properties.LoginProperties;
import com.bolt.admin.security.shiro.OnlineBean;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;

/**
 * Created by Administrator on 2020/9/18.
 */
public class OnlineSessionDAO extends EnterpriseCacheSessionDAO {

    @Autowired
    private OnlineUserService onlineUserService;

    @Autowired
    private LoginProperties loginProperties;

    public OnlineSessionDAO() {
        super();
    }

    public OnlineSessionDAO(long expireTime) {
        super();
    }

    // 创建session，保存到数据库
    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = super.doCreate(session);
        onlineUserService.save((OnlineBean)session,sessionId,loginProperties.getSession().getExpiration());
        return sessionId;
    }




    // 更新session的最后一次访问时间
    @Override
    protected void doUpdate(Session session) {
        super.doUpdate(session);
        Serializable sessionId = session.getId();
        onlineUserService.save((OnlineBean)session,sessionId,loginProperties.getSession().getExpiration());
    }
    /**
     * 根据会话ID获取会话
     *
     * @param sessionId 会话ID
     * @return ShiroSession
     */
    @Override
    protected Session doReadSession(Serializable sessionId) {
        // 先从缓存中获取session，如果没有再去数据库中获取
        Session session = super.doReadSession(sessionId);
        if(session == null){
            OnlineBean onlineBean = onlineUserService.getOne(sessionId.toString());
            return (OnlineSession)onlineBean;
        }
        return session;
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        super.update(session);
    }

    /**
     * 当会话过期/停止（如用户退出时）属性等会调用
     */
    @Override
    protected void doDelete(Session session) {
        if (null == session) {
            return;
        }
        onlineUserService.logOut(session.getId());
    }

}

 